<template>
  <div>
    <el-cascader v-model="city" :options="cityList" :props="cascaderProps" @change="onChange"></el-cascader>
  </div>
</template>
<script>
import cityJson from "@/common/city.json";
export default {
  name: "CitySelect",
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      cityList: cityJson,
      city: "",
      cascaderProps: {
        value: "code",
        label: "name",
        children: "children",
      },
    };
  },
  watch: {
    value: {
      handler: function (n, o) {
        if (n) {
          this.init();
        }
      },
      immediate: true,
    },
  },
  mounted() {
    //this.city = this.value;
  },
  methods: {
    onChange(e) {
      console.log(e);
      let list = this.cityList;
      let m = list.find((k) => k.code == e[0]);
      let n = m.children.find((k) => k.code == e[1]);
      if (n) {
        this.$emit("input", n.name);
      }
    },

    // 初始化
    init() {
      let o = this.value;
      let list = this.cityList;
      let arr = [];
      if (!o) {
        return false;
      }
      let m = list.find((k) => {
        let n = k.children.find((j) => j.name == o);
        if (n) {
          arr.push(k.code);
          arr.push(n.code);
        }
      });
      this.city = arr;
      console.log(arr);
    },
  },
};
</script>
<style lang="scss" scoped>
</style>